package com.example.jdai.jdai.ui;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jdai.jdai.MyApplication;
import com.example.jdai.jdai.R;
import com.example.jdai.jdai.config.Config;
import com.example.jdai.jdai.rest.BackRest;
import com.example.jdai.jdai.threeparty.FileUploadThread;
import com.example.jdai.jdai.util.DataAll;
import com.example.jdai.jdai.util.DataLnfo;
import com.example.jdai.jdai.util.Tools;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;

import static java.security.AccessController.getContext;

public class LnfoActivity extends Activity implements BackRest.DoLong {
    protected File cameraFile;

    @BindView(R.id.tb)
    TopBar tb;
    @BindView(R.id.ll_front)
    LinearLayout llFront;
    @BindView(R.id.ll_behind)
    LinearLayout llBehind;
    @BindView(R.id.ll_hand_front)
    LinearLayout llHandFront;
    @BindView(R.id.ll_hand_behind)
    LinearLayout llHandBehind;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_idnum)
    EditText etIdnum;
    @BindView(R.id.tv_study)
    TextView tvStudy;
    //    @BindView(R.id.address_s)
//    EditText addressS;
//    @BindView(R.id.address_x)
//    EditText addressX;
//    @BindView(R.id.address_q)
//    EditText addressQ;
    @BindView(R.id.address_j)
    EditText addressJ;
    final int Front = 0;
    final int Behind = 1;
    final int H_Front = 2;
    final int H_Behind = 3;
    @BindView(R.id.tv_front)
    TextView tvFront;
    @BindView(R.id.tv_behind)
    TextView tvBehind;
    @BindView(R.id.tv_h_front)
    TextView tvHFront;
    @BindView(R.id.tv_h_behind)
    TextView tvHBehind;
    @BindColor(R.color.mainColor)
    int select;
    @BindColor(R.color.gray_text)
    int normal;
    @BindString(R.string.no_complete)
    String onComplete;
    String imgSrc;
    @BindView(R.id.sc_content)
    ScrollView scContent;
    @BindView(R.id.et_qq)
    EditText etQq;
    @BindView(R.id.iv_front)
    ImageView ivFront;
    @BindView(R.id.iv_behind)
    ImageView ivBehind;
    @BindView(R.id.iv_hfront)
    ImageView ivHfront;
    @BindView(R.id.iv_hbehind)
    ImageView ivHbehind;
    private ProgressDialog pd;
    FileUploadThread fileUploadThread;
    @BindString(R.string.http_tip)
    String httpTip;
    @BindArray(R.array.text_study_all)
    String[] studys;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lnfo);
        ButterKnife.bind(this);
        pd = new ProgressDialog(this);
        pd.setMessage(httpTip);
        pd.setCanceledOnTouchOutside(false);
        tb.setTopBarLisener(new TopBar.TopBarLisener() {
            @Override
            public void back() {
                finish();
                saveAll();
            }

            @Override
            public void more() {
                if (checkInput()) {
                    pd.show();
                    DataAll.dataLnfo.data.put(DataLnfo.INFO_STATUS, "");
                    saveAll();
                    MyApplication.backRest.InfoOk(LnfoActivity.this);
                } else {
                    Toast.makeText(LnfoActivity.this, onComplete, Toast.LENGTH_SHORT).show();
                }

                //finish();

            }
        });
        initData();
    }

    @OnClick({R.id.ll_front, R.id.ll_behind, R.id.ll_hand_front, R.id.ll_hand_behind, R.id.tv_study})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_front:
                selectPicFromLocal(Front);
                break;
            case R.id.ll_behind:
                selectPicFromLocal(Behind);
                break;
            case R.id.ll_hand_front:
                selectPicFromLocal(H_Front);
                break;
            case R.id.ll_hand_behind:
                selectPicFromLocal(H_Behind);
                break;
            case R.id.et_name:
                break;
            case R.id.et_idnum:
                break;
            case R.id.tv_study:
                hideInput();
                new MyConnectPopuWindows(this, studys
                        , DataAll.dataLnfo.data.get(DataLnfo.STUDY))
                        .setBtOk(new MyConnectPopuWindows.MySetOk() {
                            @Override
                            public void onOkclick(int index, String itemname) {
                                DataAll.dataLnfo.data.put(DataLnfo.STUDY, itemname);
                                //DataAll.dataConnect.data.put(DataConnect.CT_OTHER_INDEX,index+"");
                                tvStudy.setText(itemname);
                            }
                        }).showAtLocation(scContent, Gravity.BOTTOM, 0, 0);
                break;
//            case R.id.address_s:
//                break;
//            case R.id.address_x:
//                break;
//            case R.id.address_q:
//                break;
            case R.id.address_j:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {

        if (resultCode == RESULT_OK) {
            Log.v("sas","sss");
            String src = cameraFile.getAbsolutePath();
//            switch (requestCode) {
//                case Front:
//                    setSfSelect(tvFront);
//                    DataAll.dataLnfo.data.put(DataLnfo.ID_FRONT, src);
//                    break;
//                case Behind:
//                    setSfSelect(tvBehind);
//                    DataAll.dataLnfo.data.put(DataLnfo.ID_BEHIND, src);
//                    break;
//                case H_Front:
//                    setSfSelect(tvHFront);
//                    DataAll.dataLnfo.data.put(DataLnfo.ID_H_FRONT, src);
//                    break;
//                case H_Behind:
//                    setSfSelect(tvHBehind);
//                    DataAll.dataLnfo.data.put(DataLnfo.ID_H_BEHIND, src);
//                    break;
//
//
//            }
            upFile(src, requestCode);
            pd.show();
        }}catch (Exception e){
            Log.v("sss",e.getMessage());
        }
    }

    @OnLongClick({R.id.ll_front, R.id.ll_behind, R.id.ll_hand_front, R.id.ll_hand_behind})
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.ll_front:
                setSfNoSelect(tvFront);
                DataAll.dataLnfo.data.put(DataLnfo.ID_FRONT, "");
                ivFront.setVisibility(View.INVISIBLE);
                break;
            case R.id.ll_behind:
                setSfNoSelect(tvBehind);
                DataAll.dataLnfo.data.put(DataLnfo.ID_BEHIND, "");
                ivBehind.setVisibility(View.INVISIBLE);
                break;
            case R.id.ll_hand_front:
                setSfNoSelect(tvHFront);
                DataAll.dataLnfo.data.put(DataLnfo.ID_H_FRONT, "");
                ivHfront.setVisibility(View.INVISIBLE);
                break;
            case R.id.ll_hand_behind:
                setSfNoSelect(tvHBehind);
                DataAll.dataLnfo.data.put(DataLnfo.ID_H_BEHIND, "");
                ivHbehind.setVisibility(View.INVISIBLE);
                break;
        }
        return true;
    }

    protected void selectPicFromLocal(int i) {
//        Intent intent;
//        if (Build.VERSION.SDK_INT < 19) {
//            intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.setType("image/*");
//
//        } else {
//            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        }
//        startActivityForResult(intent, i);
        if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this,"内存卡不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        //Log.v("sss","ssss");
        Intent intent = null;
        cameraFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+Config.APP_DOWN+System.currentTimeMillis() + ".jpg");
        //int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        //Log.e("currentapiVersion","currentapiVersion====>"+currentapiVersion);
        try {

            if (Tools.getTargetSdkVersion() < 24) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
                startActivityForResult(intent, i);
            } else {
                if (!Tools.selfPermissionGranted(this, Manifest.permission.CAMERA)) {
                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, 1);
                }

                cameraFile.getParentFile().mkdirs();
                // Log.v("23",Environment.DIRECTORY_PICTURES+System.currentTimeMillis() + ".jpg");
                // ContentValues contentValues = new ContentValues(1);
                //contentValues.put(MediaStore.Images.Media.DATA, cameraFile.getAbsolutePath());
                Uri uri = FileProvider.getUriForFile(this, "com.example.jdai.jdai.fileprovider", cameraFile);
                //Uri uri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
                // intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // intent.resolveActivity(getPackageManager());
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, i);
            }
        }catch (Exception e){
            Log.v("camere",e.toString());
        }

       //noinspection ResultOfMethodCallIgnored
//        cameraFile.getParentFile().mkdirs();
//        startActivityForResult(
//                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
//                i);
    }

    //初始化数据
    void initData() {
        // DataAll.dataLnfo=new DataLnfo();
        if ("" != DataAll.dataLnfo.data.get(DataLnfo.ID_FRONT)) {
            setSfSelect(tvFront);
            ivFront.setVisibility(View.VISIBLE);
        }
        if ("" != DataAll.dataLnfo.data.get(DataLnfo.ID_BEHIND)) {
            setSfSelect(tvBehind);
            ivBehind.setVisibility(View.VISIBLE);
        }
        if ("" != DataAll.dataLnfo.data.get(DataLnfo.ID_H_FRONT)) {
            setSfSelect(tvHFront);
            ivHfront.setVisibility(View.VISIBLE);
        }
        if ("" != DataAll.dataLnfo.data.get(DataLnfo.ID_H_BEHIND)) {
            setSfSelect(tvHBehind);
            ivHbehind.setVisibility(View.VISIBLE);
        }

        String name = DataAll.dataLnfo.data.get(DataLnfo.NAME);
        etName.setText(name);
        etName.setSelection(name.length());
        etIdnum.setText(DataAll.dataLnfo.data.get(DataLnfo.ID_NUM));
        tvStudy.setText(DataAll.dataLnfo.data.get(DataLnfo.STUDY));
//        addressS.setText(DataAll.dataLnfo.data.get(DataLnfo.ADDRESS_S));
//        addressX.setText(DataAll.dataLnfo.data.get(DataLnfo.ADDRESS_X));
//        addressQ.setText(DataAll.dataLnfo.data.get(DataLnfo.ADDRESS_Q));
        addressJ.setText(DataAll.dataLnfo.data.get(DataLnfo.ADDRESS_J));
        addressJ.setText(DataAll.dataLnfo.data.get(DataLnfo.ADDRESS_J));
        etQq.setText(DataAll.dataLnfo.data.get(DataLnfo.QQ));

    }

    //    身份证选择
    void setSfSelect(TextView tv) {
        tv.setTextColor(select);
    }

    //    身份证删除
    void setSfNoSelect(TextView tv) {
        tv.setTextColor(normal);
    }

    boolean saveAll() {
        DataAll.dataLnfo.data.put(DataLnfo.ID_NUM, etIdnum.getText().toString().trim());
        DataAll.dataLnfo.data.put(DataLnfo.NAME, etName.getText().toString().trim());
//    DataAll.dataLnfo.data.put(DataLnfo.ADDRESS_S,addressS.getText().toString().trim());
//    DataAll.dataLnfo.data.put(DataLnfo.ADDRESS_Q,addressQ.getText().toString().trim());
//    DataAll.dataLnfo.data.put(DataLnfo.ADDRESS_X,addressX.getText().toString().trim());
        DataAll.dataLnfo.data.put(DataLnfo.ADDRESS_J, addressJ.getText().toString().trim());
        DataAll.dataLnfo.data.put(DataLnfo.STUDY, tvStudy.getText().toString());
        DataAll.dataLnfo.data.put(DataLnfo.QQ, etQq.getText().toString());
        return DataAll.dataLnfo.saveAll();
    }

    @Override
    protected void onDestroy() {
        saveAll();
        finish();
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
        saveAll();
    }

    void upFile(String name, final int mark) {
        final String newName = Tools.getMD5(name);
        fileUploadThread = new FileUploadThread(name,
                newName, new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {
                        if (Config.ISDEBUG)
                            Log.v("jindu", percent + "");
                        pd.setMessage("图片已处理:" + (int) (percent * 100) + "%" + "(若没响应请重新上传)");
                    }
                }, new UpCancellationSignal() {

            @Override
            public boolean isCancelled() {
                return false;
            }
        }), new UpCompletionHandler() {
            @Override
            public void complete(final String key, final ResponseInfo respInfo,
                                 final JSONObject jsonData) {
                if (respInfo.isOK()) {
                    pd.dismiss();
                    pd.setMessage("江湖盘缠");
                    switch (mark) {
                        case Front:
                            setSfSelect(tvFront);
                            try {
                                DataAll.dataLnfo.data.put(DataLnfo.ID_FRONT, jsonData.getString("key"));
                                ivFront.setVisibility(View.VISIBLE);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        case Behind:
                            setSfSelect(tvBehind);
                            try {
                                DataAll.dataLnfo.data.put(DataLnfo.ID_BEHIND, jsonData.getString("key"));
                                ivBehind.setVisibility(View.VISIBLE);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        case H_Front:
                            setSfSelect(tvHFront);
                            try {
                                DataAll.dataLnfo.data.put(DataLnfo.ID_H_FRONT, jsonData.getString("key"));
                                ivHfront.setVisibility(View.VISIBLE);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        case H_Behind:
                            setSfSelect(tvHBehind);
                            try {
                                DataAll.dataLnfo.data.put(DataLnfo.ID_H_BEHIND, jsonData.getString("key"));
                                ivHbehind.setVisibility(View.VISIBLE);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;

                    }
                    DataAll.dataLnfo.saveAll();
                    if (Config.ISDEBUG)
                        Log.v("ok", jsonData + "");
                }
            }
        }, new FileUploadThread.onError() {
            @Override
            public void error() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(LnfoActivity.this, "出现错误(可能文件不存在)", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        fileUploadThread.start();
        //Log.v("hhh",Tools.getMD5(name));
    }

    boolean checkInput() {
        if (TextUtils.isEmpty(etIdnum.getText().toString().trim()) ||
                TextUtils.isEmpty(etName.getText().toString().trim()) ||
                TextUtils.isEmpty(tvStudy.getText().toString().trim()) ||
                TextUtils.isEmpty(addressJ.getText().toString().trim()) ||
                TextUtils.isEmpty(etQq.getText().toString().trim()) ||
                "".equals(DataAll.dataLnfo.data.get(DataLnfo.ID_FRONT)) ||
                "".equals(DataAll.dataLnfo.data.get(DataLnfo.ID_BEHIND)) ||
                "".equals(DataAll.dataLnfo.data.get(DataLnfo.ID_H_FRONT)) ||
                "".equals(DataAll.dataLnfo.data.get(DataLnfo.ID_H_BEHIND))
                ) {
            return false;
        }
        return true;
    }

    @Override
    public void doDone(int mark, Map str) {
        switch (mark) {
            case 0:
                pd.dismiss();
                //startActivity(new Intent(LnfoActivity.this, ConnectActivity.class));
                MyApplication.startNext(LnfoActivity.this);
                finish();
                break;
            case 2:
                pd.dismiss();
                Toast.makeText(MyApplication.applicationContext, "出现错误", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if(requestCode==1){
            if (!Tools.selfPermissionGranted(this, Manifest.permission.CAMERA)) {
                Toast.makeText(this,"请打开相机",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
